package com.cf.contraband;

import com.cf.contraband.sensitive.KWSeeker;
import com.cf.contraband.sensitive.SensitiveWordResult;
import com.cf.contraband.sensitive.SimpleKWSeekerProcessor;
import org.apache.commons.lang3.StringUtils;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 敏感词过滤器，以过滤速度优化为主。<br/>
 * * 获取默认的单例：{@link #DEFAULT}
 */
public class BannerFilter implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 默认的单例，使用自带的敏感词库
     */
    public static BannerFilter DEFAULT;

    private SimpleKWSeekerProcessor processor;


    public BannerFilter() {
    }

    public BannerFilter(BufferedReader reader) {
        try {
            List<String> dataList = new ArrayList<String>();
            for (String line = reader.readLine(); line != null; line = reader.readLine()) {
                dataList.add(line);
            }
            processor = SimpleKWSeekerProcessor.newInstance(dataList);
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public BannerFilter init(String wordPath) throws FileNotFoundException {
        if (StringUtils.isNotEmpty(wordPath)) {
            DEFAULT = new BannerFilter(new BufferedReader(new InputStreamReader(new FileInputStream(wordPath), StandardCharsets.UTF_8)));

        } else {
            DEFAULT = new BannerFilter(new BufferedReader(new InputStreamReader(this.getClass().getResourceAsStream("/dic/mgc/sensi_words.txt"), StandardCharsets.UTF_8)));
        }
        return this;
    }

    /**
     * 对句子进行敏感词过滤<br/>
     * </code>
     */
    public BannerResp process(String sentence) {
        BannerResp resp = new BannerResp();
        KWSeeker seeker = processor.getKWSeeker("default");
        List<SensitiveWordResult> words = seeker.findWords(sentence);

        if (!words.isEmpty()) {
            resp.setHasSensitiveWords(true);
            for (SensitiveWordResult result : words) {
                resp.addSensitiveWord(result.getWord());
            }
            resp.setFilterStr(seeker.replaceWords(sentence));
        } else {
            resp.setFilterStr(sentence);
        }
        return resp;
    }
}
